package cn.iocoder.yudao.module.shop.service.order;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.iocoder.yudao.module.shop.dal.dataobject.item.ShopItemDO;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderItemDO;
import cn.iocoder.yudao.module.shop.dal.mysql.order.ShopOrderItemMapper;
import cn.iocoder.yudao.module.shop.service.item.ShopItemService;
import cn.iocoder.yudao.module.shop.service.order.dto.ShopOrderItemHandleDTO;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
@Validated
public class ShopOrderItemServiceImpl implements ShopOrderItemService{
    @Resource
    private ShopOrderItemMapper itemMapper;

    @Resource
    private ShopItemService shopItemService;

    @Override
    public List<ShopOrderItemDO> getShopOrderItemList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return itemMapper.selectBatchIds(ids);
    }

    @Override
    public List<ShopOrderItemDO> getShopOrderItemListByOrderId(Collection<Long> orderIds) {
        if(CollUtil.isEmpty(orderIds)){
            return ListUtil.empty();
        }

        return itemMapper.selectListByOrderId(orderIds);
    }

    @Override
    public List<ShopOrderItemDO> getShopOrderItemListByOrderId(Long orderId){
        return itemMapper.selectListByOrderId(orderId);
    }


    // 获取结算支数，或者固定手工费
    @Override
    public ShopOrderItemHandleDTO getHandleByOrderId(Long orderId){
        List<ShopOrderItemDO> orderItemDOList = getShopOrderItemListByOrderId(orderId);
        Integer handleCount = 0;
        Integer extHandlePrice = 0;
        Integer handleRate = -1;

        List<Long> shopItemList = new ArrayList<>();
        for(int i = 0; i<orderItemDOList.size(); i++){
            shopItemList.add(orderItemDOList.get(i).getOptItemId());
        }

        //有个问题。一个order仅适用于约一个项目
        List<ShopItemDO> shopItemDOList = shopItemService.getItemList(shopItemList);
        for(int i = 0; i<shopItemDOList.size(); i++){
            if(shopItemDOList.get(i).getHandleRate() > 0){
                handleRate = shopItemDOList.get(i).getHandleRate();
            }else {
                if(shopItemDOList.get(i).getHandlePrice() < 0){
                    handleCount += shopItemDOList.get(i).getHandleCount();
                }else{
                    extHandlePrice += shopItemDOList.get(i).getHandlePrice();
                }
            }
        }

        ShopOrderItemHandleDTO result = new ShopOrderItemHandleDTO();
        result.setHandleCount(handleCount);
        result.setExtHandlePrice(extHandlePrice);
        result.setHandleRate(handleRate);

        return result;

    }
}
